#! /usr/bin/env python

import os, parser, sys

def is_iterable(obj):
    try: 
        iter(obj)
        return True
    except TypeError: 
        return False

def is_term(s):
    try:
        return (len(s) == 3 and issubclass(type(s[1]), basestring))
    except TypeError:
        return False

def find_defs(st, filename, code):
    i = iter(st)

    for s in i:
        if not is_iterable(s):
            continue
        
        elif is_term(s):
            if s[1] == 'def':
                s = i.next()
                print '%s\t%s\t%s\t%s' % (s[1],
                                          s[2],
                                          filename,
                                          code[s[2] - 1])

        else:
            find_defs(s, filename, code)

def process_python_file(filename):
    with open(filename, 'r') as f:
        code = f.read()
    st = parser.suite(code)
    code = code.split('\n')
    sttups = parser.st2tuple(st, line_info=True)
    if is_iterable(sttups):
        find_defs(sttups, filename, code)

def main():
    for filename in sys.argv[1:]:
        ext = os.path.splitext(filename)[1].lower()
        if ext not in ('.py', '.pyw'):
            os.system('gtags-parser -dt %s' % filename)
        else:
            process_python_file(filename)

if __name__ == '__main__':
    main()
